<template>
    <div class="taskdetailcontainer" v-if="internaltask != null">
        <div class="taskheader">
            <div class="title-t">{{ internaltask.Title }}</div>
            <div class="subtitle-t"><img class="location-icon" src="/img/ic_location_inline.png" /><span>{{
                internaltask.Location }}&nbsp;</span></div>

            <b-dropdown :triggers="['click']" aria-role="list" style="position:absolute;right: 28px;top:28px"
                position="is-bottom-left" :append-to-body="true">
                <template #trigger>
                    <div class="roundbutton editbutton">
                        <div
                            style="background-image: url(/img/ic_edit.png);background-position: center center; background-size: 90% 90%; background-repeat: no-repeat; width: 100%; height:100%">
                        </div>
                    </div>
                </template>


                <b-dropdown-item aria-role="listitem" @click="editcontent" class="taskedit-dropdown">
                    <span v-if="editingcontent">保存内容</span><span v-else>编辑内容</span>
                </b-dropdown-item>
                <b-dropdown-item aria-role="listitem" @click="edittask" class="taskedit-dropdown">编辑任务</b-dropdown-item>
                <b-dropdown-item aria-role="listitem" v-if="internaltask.IsCompleted" @click="reopentask" class="taskedit-dropdown">重启任务</b-dropdown-item>
                <b-dropdown-item aria-role="listitem" @click="toptask" v-if="!internaltask.IsCompleted" class="taskedit-dropdown">置顶任务</b-dropdown-item>
                <b-dropdown-item aria-role="listitem" @click="deltask" class="taskedit-dropdown">删除任务</b-dropdown-item>


            </b-dropdown>


        </div>
        <div class="borderhr"></div>
        <div class="taskcontent">
            <div class="markdown-container" v-if="!editingcontent" v-html="htmlcontent">

            </div>
            <template v-else>
                <div class="mdheader">

                    <b-dropdown :append-to-body="true" style="width: 22%;">
                        <template #trigger>

                            <GenshinButton img="/img/ic_image.png" title="插入图片" width="100%"></GenshinButton>
                        </template>
                        <b-dropdown-item aria-role="listitem" class="taskedit-dropdown"
                            @click="chooseImg('/api/todo/img/select')">选择图片...</b-dropdown-item>
                        <b-dropdown-item aria-role="listitem" class="taskedit-dropdown"
                            @click="chooseImg('/api/todo/img/paste')">粘贴图片</b-dropdown-item>
                    </b-dropdown>
                    <b-dropdown :append-to-body="true" style="width: 22%; margin-left: 0px;">
                        <template #trigger>


                            <GenshinButton img="/img/ic_file.png" title="插入文件" width="100%"></GenshinButton>
                        </template>

                        <b-dropdown-item aria-role="listitem" class="taskedit-dropdown"
                            @click="chooseFile('/api/todo/reqfile')">插入文件</b-dropdown-item>
                        <b-dropdown-item aria-role="listitem" class="taskedit-dropdown"
                            @click="chooseFile('/api/todo/reqfolder')">插入文件夹</b-dropdown-item>
                    </b-dropdown>
                    <GenshinButton img="/img/ic_link.png" title="插入链接" width="22%" @click="insertlink"></GenshinButton>
                    <GenshinButton img="/img/ic_save.png" title="保存修改" width="22%" @click="editcontent"></GenshinButton>
                </div>
                <textarea ref="mdeditor" class="mdeditor" v-model="internaltask.Content"></textarea>
            </template>
        </div>

        <div v-if="showtimer" class="timerdisplay">
            <img class="location-icon" style="margin-top: 2px;" src="/img/ic_timer.png" />
            <span style="color:transparent;text-shadow: none;">|</span>
            <span>{{ timercontent }}</span>
        </div>
        <template v-if="internaltask.RelatedFiles.length > 0 && !editingcontent">
            <div
                style="width:calc(100% - 64px);height:2px;background-color: #ffffff20; margin:0px 32px; flex-shrink: 0;">
            </div>
            <div class="taskrefer">
                <div class="relatedfile-title">任务追踪：</div>
                <div class="relatedfile-container">
                    <div v-for="file in internaltask.RelatedFiles" @click="openfile(file)" :key="file.Path"
                        class="relatedfile-entry">
                        <p>{{ file.DisplayName }}</p>
                    </div>


                </div>
            </div>
        </template>
        <div v-else style="flex-shrink:0;height:32px"> </div>
        <ElTimer :interval="19198" @tick="updateTimer" v-if="showtimer"></ElTimer>
    </div>
</template>
<script>

import ElTimer from "../components/ElTimer.vue";

import GenshinButton from "../components/GenshinButton.vue";

export default {
    name: "TaskDetailView",
    components: { ElTimer, GenshinButton },
    props: ["task"],
    data() {
        return {
            internaltask: null,
            htmlcontent: "",
            editingcontent: false,
            timercontent: "哼哼哼啊啊啊啊啊啊啊啊啊啊啊啊啊啊",
            showtimer: false,
        };
    },
    methods: {
        editcontent() {
            this.editingcontent = !this.editingcontent;
            // exit editing.
            if (this.editingcontent == false) {
                this.htmlcontent = window.marked.parse(this.internaltask.Content);
                this.$nextTick(function () {

                    this.postProcessMarkdown();
                })
                this.onchange();
            }
            else {
                this.$nextTick(function () {
                    this.$refs.mdeditor.focus();
                });
            }
            this.$emit("editStateChanged", this.editingcontent);
        },
        edittask() {
            this.$emit("reqedit");
        },
        reopentask() {
            this.$emit("reopen");
        },
        onchange() {
            this.$emit("changed", this.internaltask);
        },
        deltask() {
            this.$emit("delete");
        },

        toptask() {
            this.$emit("totop");
        },
        postProcessMarkdown() {
            const checkboxes = document.querySelectorAll('.markdown-container input[type="checkbox"]');
            for (let index = 0; index < checkboxes.length; index++) {
                const checkbox = checkboxes[index];
                const fixed_index = index;

                const li = checkbox.parentNode;
                li.classList.add("markdown-checkbox-item");
                if (checkbox.checked) {
                    li.classList.add('markdown-checkbox-item-checked');
                } else {
                    li.classList.add('markdown-checkbox-item-unchecked');
                }
                window.__cached_function_pointer_toggleMarkdownCheckbox = this.toggleMarkdownCheckbox;
                li.addEventListener("click", function (eve) {

                    eve.stopPropagation();
                    checkbox.checked = !checkbox.checked;

                    li.classList.remove('markdown-checkbox-item-checked');
                    li.classList.remove('markdown-checkbox-item-unchecked');
                    if (checkbox.checked) {
                        li.classList.add('markdown-checkbox-item-checked');
                    } else {
                        li.classList.add('markdown-checkbox-item-unchecked');
                    }
                    window.__cached_function_pointer_toggleMarkdownCheckbox(fixed_index, checkbox.checked);
                    return false;
                });
            }

        },

        toggleMarkdownCheckbox(which, state) {
            var oldtext = this.internaltask.Content;
            var newtext = this.setMarkdownCheckboxState(oldtext,which,state);
            this.internaltask.Content = newtext;
            this.$emit("changed", this.internaltask);
        },
        setMarkdownCheckboxState(markdown_str, which, isChecked) {
            const regex = /^([ \t]*)- \[(x| )\] (.*)$/gm;
            let match;
            let count = 0;

            while ((match = regex.exec(markdown_str)) !== null) {
                if (count === which) {
                    const indent = match[1];
                    const checkboxState = isChecked ? 'x' : ' ';
                    const replacement = `${indent}- [${checkboxState}] ${match[3]}`;
                    markdown_str = markdown_str.replace(match[0], replacement);
                    break;
                }
                count++;
            }

            return markdown_str;
        },
        chooseImg(apiuri) {
            window.$.ajax(apiuri, null).then(result => {
                var imgPaths = JSON.parse(result);
                if (imgPaths.length == 0) {
                    this.$buefy.toast.open('未选择图片')
                    return;
                }
                var imageToInsert = "\r\n";
                imgPaths.forEach(element => {
                    imageToInsert += "![](/api/todo/img/get/" + element + ")";
                });
                this.insertContent(imageToInsert);
            }).catch(err => {
                this.$buefy.toast.open({
                    duration: 5000,
                    message: `请求失败` + err,
                    position: 'is-top',
                    type: 'is-danger'
                });
            });
        },

        chooseFile(apiuri) {
            window.$.ajax(apiuri, null).then(result => {
                var files = JSON.parse(result);
                if (files.length == 0) {
                    this.$buefy.toast.open('未选择文件');
                    return;
                }
                var fileLinks = "\r\n";
                files.forEach(element => {
                    fileLinks += "[" + element.DisplayName + "](/api/todo/v2/openfile?" + encodeURI(element.Path) + ")";
                });
                this.insertContent(fileLinks);

            }).catch(err => {
                this.$buefy.toast.open({
                    duration: 5000,
                    message: `请求失败` + err,
                    position: 'is-top',
                    type: 'is-danger'
                });
            });
        },

        insertlink() {
            this.insertContent(" [在这里输入网址标题](在这里输入网址链接) ");
        },

        insertContent(str) {
            window.$.insertInTextarea(this.$refs.mdeditor, str);
            this.internaltask.Content = this.$refs.mdeditor.value;
        },


        openfile(file) {
            this.$buefy.toast.open({
                duration: 5000,
                message: "正在打开：" + file.Path,
                position: 'is-bottom',
            });
            window.$.postJson("/api/todo/openfile", file).then((result) => {
                setTimeout(() => {
                    window.$.ajax("/api/ui/close")
                }, 1000);
            }).catch((err) => { });

        },

        onTaskChanged() {

            if ((!this.internaltask) || this.internaltask.Content == null || this.internaltask.Content == "") {
                this.htmlcontent = "";
            }
            else {

                this.htmlcontent = window.marked.parse(this.internaltask.Content);
            }
            this.$nextTick(function () {

                this.postProcessMarkdown();
            })
            this.showtimer = false;
            if (this.internaltask.IsCompleted) {
                this.showtimer = true;
                this.updateTimer();
            }
            else {
                if (this.internaltask.EndDate != null) {
                    this.showtimer = true;
                    this.updateTimer();
                }
            }

        },

        updateTimer() {
            if (this.internaltask.IsCompleted) {
                this.timercontent = "完成时间：" + window.$.formatDate(this.internaltask.CompleteTime);
            }
            else {
                if (this.internaltask.EndDate != null) {
                    var currentTime = new Date().getTime();
                    var dueTime = new Date(this.internaltask.EndDate).getTime();

                    var estimateTime = dueTime - currentTime;

                    var expired = estimateTime < 0;

                    if (expired) {
                        estimateTime = -estimateTime;
                    }

                    var msg = "";
                    if (expired) {
                        msg += "已过期：";
                    }
                    else {
                        msg += "剩余可完成时间：";
                    }
                    msg += this.msToSpanStr(estimateTime);
                    this.timercontent = msg;
                }
            }
        },

        msToSpanStr(ms) {
            var msg = "";
            var day = Math.floor(ms / 86400000);
            var hour = Math.floor((ms % 86400000) / 3600000);
            var minute = Math.floor((ms % 3600000) / 60000);

            if (day > 0) {
                msg += "" + day + "天";
            }
            if (day > 0 || hour > 0) {
                msg += "" + hour + "小时";
            }
            if (day == 0 && hour == 0) {
                msg += "" + minute + "分钟";
            }
            return msg;
        }


    },
    mounted() {
        this.internaltask = this.task;
        this.onTaskChanged();
    },
    watch: {
        "task": function (newval) {
            this.internaltask = newval;
            this.editingcontent = false;
            this.onTaskChanged();
        }
    }
};
</script>

<style scoped>
.taskdetailcontainer {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.taskheader {
    flex-shrink: 0;
    height: 100px;
    width: 100%;
    position: relative;
}

.taskcontent {
    width: 100%;
    flex-grow: 1;
    overflow-x: none;
    overflow-y: scroll;
}

.taskrefer {

    height: 150px;
    width: 100%;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
}


.borderhr {
    border-image: url(/img/hr_big_border.png) 45 113;
    width: calc(100%);
    height: 12px;
    border-image-width: 14px 35px 0px 35px;
    border-top: 14px;
    margin-left: 0px;
    margin-right: 0px;
    border-image-outset: 2px 0px;
    opacity: 0.5;
    flex-shrink: 0;
}

.taskheader>.title-t {
    position: absolute;
    font-weight: bold;
    font-size: 26px;
    top: 17px;
    left: 36px;
    color: rgb(237, 229, 218);
    text-shadow: 0 0 3px rgba(0, 0, 0, 0.404);
    ;
}

.taskheader>.subtitle-t {
    position: absolute;
    bottom: 14px;
    left: 33px;
    color: rgb(216, 202, 175);
    text-shadow: 0 0 3px rgba(0, 0, 0, 0.404);
    ;
    font-weight: bold;
    font-size: 16px;
}

.location-icon {
    width: 20px;
    height: 20px;
    float: left;
    margin-right: 5px;
    margin-top: 3px;
    filter: drop-shadow(0px 0px 2px rgba(0, 0, 0, 0.2));
}

.mdeditor {
    width: calc(100% - 60px);
    height: calc(100% - 30px - 60px);
    color: white;
    font-size: 20px;
    font-family: 'FiraCode', 'Consolas', 'Ubuntu Mono', 'Courier New', Courier, monospace;
    border: none;
    background-color: rgba(0, 0, 0, 0.384);
    margin: 10px 30px;
    padding: 20px;
    resize: none;
}


.mdheader {
    width: calc(100% - 60px);
    height: 60px;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;

    margin: 0px 30px;
}


.relatedfile-title {
    margin-left: 36px;
    font-weight: bold;
    font-size: 20px;
    color: white;
    text-shadow: 0 0 3px rgba(0, 0, 0, 0.404);
    ;
}

.relatedfile-container {
    flex-grow: 1;
    overflow-x: hidden;
    overflow-y: scroll;
    margin: 1px 35px 5px 35px;
}



.relatedfile-entry {
    padding: 3px 15px;
    margin: 1px 0px;
    margin-bottom: 2px;
    font-size: 18px;
    font-weight: 400;
    color: rgb(253, 249, 240);
    transition-duration: 250ms;
    text-shadow: 0 0 3px rgba(0, 0, 0, 0.404);
    cursor: pointer;
}



.relatedfile-entry:hover {
    padding: 3px 20px;
    text-decoration: underline;
}



.relatedfile-entry>p::before {
    content: "";
    width: 20px;
    height: 20px;
    background-image: url(/img/blockquote_before.png);
    background-size: 100%;
    background-repeat: no-repeat;
    display: block;
    float: left;
    margin-right: 9px;
    margin-top: 4px;
}

.taskedit-dropdown {
    font-size: 27px;
    line-height: 40px;
}

.timerdisplay {
    padding: 3px 15px;
    margin: 5px 0px;
    background-color: rgba(0, 0, 0, 0.151);
    color: rgb(252, 222, 79);
    margin: 2px 32px;
    text-shadow: 0 0 3px rgba(0, 0, 0, 0.404);
    flex-shrink: 0;
}
</style>